package lunchy.mvc.views;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.eclipse.swt.events.ModifyEvent;
import org.eclipse.swt.events.ModifyListener;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.MouseListener;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.events.SelectionListener;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.MessageBox;
import org.eclipse.swt.widgets.Spinner;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.custom.ScrolledComposite;

import lunchy.data.classes.CLunchyUser;
import lunchy.data.interfaces.ILunchyMenuGroup;
import lunchy.data.interfaces.ILunchyMenuItem;
import lunchy.data.interfaces.ILunchyUser;
import lunchy.main.CLunchyApplication;
import lunchy.mvc.controllers.CLunchyMenuController;

import org.eclipse.wb.swt.SWTResourceManager;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.MenuItem;

public class CLunchyMenuView
{
	private Shell shellMenu;
	private CLunchyMenuController controller;
	
	private Label allPriceLabel;
	private Map<ILunchyMenuItem, Spinner> countMap;
	private Map<Spinner, Label> priceMap;
	private Menu mainMenu;
	private Composite child;
	private ScrolledComposite menuComposite;
	
	public CLunchyMenuView()
	{	
		controller = new CLunchyMenuController();

		countMap = new HashMap<ILunchyMenuItem, Spinner>();
		priceMap = new HashMap<Spinner, Label>();
		
		shellMenu = new Shell(CLunchyApplication.getInstance().display, SWT.CLOSE | SWT.TITLE | SWT.MIN);
		shellMenu.setMinimumSize(new Point(200, 200));
		shellMenu.setText("LunchY");
		shellMenu.setSize(580, 480);
		
		initUI();
		
		shellMenu.open();
        
        while (!shellMenu.isDisposed())
        {
        	if (!CLunchyApplication.getInstance().display.readAndDispatch())
        		CLunchyApplication.getInstance().display.sleep();
        }
	}
	
	private void initUI()
	{
		shellMenu.setLayout(null);

		//Header
	    Label label = new Label(shellMenu, SWT.NONE);
	    label.setBounds(15, 15, 90, 14);
	    label.setText("Наименование");
	    
	    Label lblNewLabel = new Label(shellMenu, SWT.NONE);
	    lblNewLabel.setBounds(307, 15, 70, 14);
	    lblNewLabel.setText("Стоимость");
	    
	    Label label_1 = new Label(shellMenu, SWT.NONE);
	    label_1.setBounds(380, 15, 70, 14);
	    label_1.setText("Количество");
	    
	    Label label_2 = new Label(shellMenu, SWT.NONE);
	    label_2.setBounds(460, 15, 110, 14);
	    label_2.setText("Общая стоимость");
	    
	    Label headerSeparator = new Label(shellMenu, SWT.SEPARATOR | SWT.HORIZONTAL);
	    headerSeparator.setBounds(10, 35, 560, 2);
	    
	    //Footer
	    
	    Label footerSeparator = new Label(shellMenu, SWT.SEPARATOR | SWT.HORIZONTAL);
	    footerSeparator.setBounds(15, 420, 560, 2);
	    
	    Button orderButton = new Button(shellMenu, SWT.NONE);
	    orderButton.setBounds(15, 426, 94, 28);
	    orderButton.setText("Заказать");
	    orderButton.addMouseListener(
	    	new MouseListener()
	    	{
				@Override
				public void mouseUp(MouseEvent e)
				{
					if(controller.saveOrder())
					{
						MessageBox successSaveMessage = new MessageBox(shellMenu, SWT.ICON_INFORMATION);
						successSaveMessage.setText("Сохранение заказа");
						successSaveMessage.setMessage("Ваш заказ успешно сохранен!");
						successSaveMessage.open();
					}
					
					initAppMenu();
				}
				
				@Override
				public void mouseDown(MouseEvent e)
				{	
					
				}
				
				@Override
				public void mouseDoubleClick(MouseEvent e)
				{
					
				}
	    	}
	    );
	    
	    allPriceLabel = new Label(shellMenu, SWT.NONE);
	    allPriceLabel.setBounds(440, 430, 120, 20);
	    allPriceLabel.setText("Итого: 0 руб.");
		
		initMenu();
		
		initAppMenu();
	}
	
	private void initAppMenu()
	{
		mainMenu = new Menu(shellMenu, SWT.BAR);
		ILunchyUser user = CLunchyApplication.getInstance().currentUser;
		
		MenuItem mainMenuAdminItem = new MenuItem(mainMenu, SWT.CASCADE);
		mainMenuAdminItem.setText("LunchY");
		
		Menu mainMenuAdmin = new Menu(mainMenuAdminItem);
		MenuItem adminLoginItem = new MenuItem(mainMenuAdmin, SWT.PUSH);
		
		if(user == null)
		{
			adminLoginItem.setText("Войти...");
			adminLoginItem.addSelectionListener(
				new SelectionListener()
				{
					@Override
					public void widgetSelected(SelectionEvent e)
					{
						CLunchyApplication.getInstance().debug("Menu Item Clicked: Login...");
						controller.showLoginDialog();
						initAppMenu();
					}
					
					@Override
					public void widgetDefaultSelected(SelectionEvent e)
					{		
					}
				}
			);
		}
		else
		{
			adminLoginItem.setText("Выход (" + user.getLogin() + ")...");
			adminLoginItem.addSelectionListener(
				new SelectionListener()
				{
					@Override
					public void widgetSelected(SelectionEvent e)
					{
						CLunchyApplication.getInstance().debug("Menu Item Clicked: Logout...");
						CLunchyApplication.getInstance().currentUser = null;
						initAppMenu();
					}
					
					@Override
					public void widgetDefaultSelected(SelectionEvent e)
					{		
					}
				}
			);
		}
		
		if(user != null && user.getIsAdmin())
		{
			MenuItem adminMenuEditItem = new MenuItem(mainMenuAdmin, SWT.PUSH);
			adminMenuEditItem.setText("Редактировать меню...");
			adminMenuEditItem.addSelectionListener(
				new SelectionListener()
				{
					@Override
					public void widgetSelected(SelectionEvent e)
					{
						CLunchyApplication.getInstance().debug("Menu Item Clicked: Menu Edit...");
						controller.showMenuEditWindow();
						initMenu();
					}
					
					@Override
					public void widgetDefaultSelected(SelectionEvent e)
					{		
					}
				}
			);
			
			MenuItem adminUsersEditItem = new MenuItem(mainMenuAdmin, SWT.PUSH);
			adminUsersEditItem.setText("Редактировать пользователей...");
			adminUsersEditItem.addSelectionListener(
				new SelectionListener()
				{
					@Override
					public void widgetSelected(SelectionEvent e)
					{
						CLunchyApplication.getInstance().debug("Menu Item Clicked: Users Edit...");
					}
					
					@Override
					public void widgetDefaultSelected(SelectionEvent e)
					{		
					}
				}
			);
		}
	    
		mainMenuAdminItem.setMenu(mainMenuAdmin);
		
		shellMenu.setMenuBar(mainMenu);
		mainMenu.setDefaultItem(mainMenuAdminItem);
	}
	
	private void initMenu()
	{	
		CLunchyApplication.getInstance().debug("[CLunchyMenuView] loading menu...");
		
		int i = 0;
		
		if(menuComposite != null)
			menuComposite.dispose();

		menuComposite = new ScrolledComposite(shellMenu, SWT.H_SCROLL | SWT.V_SCROLL);
		menuComposite.setBounds(0, 43, 560, 367);
		menuComposite.setMinSize(580, 410);
			
		child = new Composite(menuComposite, SWT.NONE);
		child.setLocation(0, 0);	
	    child.setLayout(null);
	    
	    menuComposite.setContent(child);
	    
		countMap.clear();
		priceMap.clear();
		
		for (ILunchyMenuGroup currentGroup : controller.getMenuGroups())
		{
			////Group
			Label groupLabel = new Label(child, SWT.NONE);
			groupLabel.setForeground(SWTResourceManager.getColor(SWT.COLOR_BLACK));
			groupLabel.setFont(SWTResourceManager.getFont("Lucida Grande", 14, SWT.BOLD));
			groupLabel.setBounds(15, 43 * i, 535, 22);
			groupLabel.setText(currentGroup.getName());
		    
			CLunchyApplication.getInstance().debug("[CLunchyMenuView] group: " + currentGroup.getName());
			
		    i++;
		    
		    for (ILunchyMenuItem currentItem : currentGroup.getItems())
		    {	
			    ////Item
		    	CLunchyApplication.getInstance().debug("[CLunchyMenuView] item: " + currentItem.getName());
		    	
		    	Label itemNameLabel = new Label(child, SWT.NONE);
			    itemNameLabel.setBounds(15, 43 * i, 85, 22);
			    itemNameLabel.setText(currentItem.getName());
			    
			    Label itemPriceLabel = new Label(child, SWT.NONE);
			    itemPriceLabel.setAlignment(SWT.LEFT);
			    itemPriceLabel.setBounds(309, 43 * i, 70, 22);
			    itemPriceLabel.setText(currentItem.getPrice() + " руб.");

			    Spinner itemCountInput = new Spinner(child, SWT.BORDER);
			    itemCountInput.setBounds(385, 43 * i, 67, 22);
			    itemCountInput.addModifyListener(
			    	new ModifyListener()
			    	{
			    		@Override
			    		public void modifyText(ModifyEvent e)
			    		{
			    			Label sumLabel = priceMap.get(e.widget);
			    			int itemPrice = 0, itemCount = 0, allPrice = 0;
			    			
			    			Set<Entry<ILunchyMenuItem, Spinner>> menuItems = countMap.entrySet();
			    			
			    			// Общая цена блюда
			    			for (Entry<ILunchyMenuItem, Spinner> item : menuItems)
			    			{
			    				if(item.getValue().equals(e.widget))
			    				{
				    				try
				    				{
				    					itemCount = Integer.parseInt(item.getValue().getText());
				    					itemPrice = item.getKey().getPrice() * itemCount;
				    				}
				    				catch(NumberFormatException ex)
				    				{
				    					itemCount = itemPrice = 0;
				    				}
	
				    				if(itemPrice < 0)
				    					itemPrice = 0;
				    				
				    				controller.AddOrUpdateItemInOrder(item.getKey(), itemCount);
				    				sumLabel.setText(String.format("%1d руб.", itemPrice));
			    				}
			    			}
			    			
			    			// Общая цена заказа
			    			for (Entry<ILunchyMenuItem, Spinner> item : menuItems)
			    			{
			    				try
			    				{
			    					itemPrice = item.getKey().getPrice() * Integer.parseInt(item.getValue().getText());
			    				}
			    				catch(NumberFormatException ex)
			    				{
			    					itemPrice = 0;
			    				}

			    				if(itemPrice < 0)
			    					itemPrice = 0;
			    				
			    				allPrice += itemPrice;
			    			}
			    			allPriceLabel.setText(String.format("Итого: %1d руб.", allPrice));
			    		}
			    	}
			    );
			    
			    Label itemSumPriceLabel = new Label(child, SWT.NONE);
			    itemSumPriceLabel.setAlignment(SWT.LEFT);
			    itemSumPriceLabel.setBounds(470, 43 * i, 140, 22);
			    itemSumPriceLabel.setText("0 руб.");
			    
			    countMap.put(currentItem, itemCountInput);
			    priceMap.put(itemCountInput, itemSumPriceLabel);
			    
			    i++;
		    }
		}
		
		child.setSize(560, 43 * i);
		
		CLunchyApplication.getInstance().debug("[CLunchyMenuView] menu loaded...");
	}
}